<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import InTagLine from "./InTagLine.vue";

const model = defineModel<{ [key: string]: string }>();
const emit = defineEmits(["change"]);

defineProps<{
  edit?: boolean;
}>();

type KVObject = {
  key: string;
  value: string;
};

const kvs = ref<KVObject[]>([]);

const reloadKvs = () => {
  kvs.value = Object.entries(model.value ?? {}).map(([key, value]) => ({
    key,
    value
  }));
};

const syncToModel = () => {
  const newModel = {} as { [key: string]: string };
  kvs.value.forEach(({ key, value }) => {
    newModel[key] = value;
  });
  model.value = newModel;
  emit("change", newModel);
};

const deleteKV = (key: string) => {
  kvs.value = kvs.value.filter(item => item.key !== key);
  syncToModel();
};

onMounted(() => {
  reloadKvs();
});

watch(
  () => model.value,
  () => {
    console.log("model changed");
    reloadKvs();
  },
  { deep: true }
);
</script>

<template>
  <el-space wrap>
    <InTagLine
      v-for="(kv, idx) in kvs"
      :key="kv.key"
      v-model:model-value="kvs[idx]"
      :edit="edit"
      @change="syncToModel"
      @delete="deleteKV"
    />
    <el-button
      v-if="edit"
      type="primary"
      icon="Plus"
      size="small"
      style="height: 40px"
      plain
      @click="kvs.push({ key: '', value: '' })"
      ><span>添加</span>
    </el-button>
  </el-space>
</template>
<style lang="scss" scoped></style>
